package com.heima.common.aliyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Getter
@Setter
@Component
@SuppressWarnings("ConfigurationProperties")
@ConfigurationProperties(prefix = "aliyun")

public class TextAutoRoute {

    private String accessKeyId;
    private String secret;

    public Map greeTextScan(String content) throws Exception {
        Map<String, String> resultMap = new HashMap<>();
        Config config = new Config();
        config.setAccessKeyId(accessKeyId); // 设置访问密钥ID
        config.setAccessKeySecret(secret); // 设置访问密钥Secret
        config.setRegionId("cn-shanghai"); // 设置接入区域
        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // 设置接入地址
        config.setReadTimeout(6000); // 设置连接时超时时间，单位毫秒（ms）
        config.setConnectTimeout(3000); // 设置读取时超时时间，单位毫秒（ms）

        Client client = new Client(config); // 创建Client对象

        RuntimeOptions runtime = new RuntimeOptions(); // 创建RuntimeOptions对象并设置运行参数
        runtime.readTimeout = 10000; // 设置读取时超时时间，单位毫秒（ms）
        runtime.connectTimeout = 10000; // 设置连接时超时时间，单位毫秒（ms）

        JSONObject serviceParameters = new JSONObject(); // 创建JSONObject对象用于存储服务参数
        serviceParameters.put("content", content); // 设置文本内容

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            System.out.println("text moderation content is empty"); // 如果文本内容为空，则输出提示信息并返回
            return null;
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest(); // 创建TextModerationRequest对象
        textModerationRequest.setService("comment_detection"); // 设置文本检测服务的service code
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString()); // 设置文本检测服务的参数

        try {
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime); // 调用方法获取检测结果

            if (response != null) {
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 服务端错误，区域切换到cn-beijing
                    config.setRegionId("cn-beijing");
                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
                    client = new Client(config);
                    response = client.textModerationWithOptions(textModerationRequest, runtime);
                }
            }

            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
//                    System.out.println(result);
//                    System.out.println(JSON.toJSONString(result)); // 打印检测结果
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
//                        System.out.println("labels = [" + data.getLabels() + "]"); // 打印标签
                        resultMap.put("labels",  data.getLabels());
//                        System.out.println("reason = [" + data.getReason() + "]"); // 打印理由
                        resultMap.put("reason",  data.getReason());
                    } else {
                        System.out.println("text moderation not success. code:" + code); // 输出检测失败的提示信息
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode()); // 输出响应失败的提示信息
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultMap;
    }
}

